<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>

<meta charset="utf-8">
<meta name="generator" content="quarto-1.2.198">

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">


<title>R语言医学数据科学入门 - 5&nbsp; 数据清洗</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
  width: 0.8em;
  margin: 0 0.8em 0.2em -1.6em;
  vertical-align: middle;
}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
  { counter-reset: source-line 0; }
pre.numberSource code > span
  { position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
  { content: counter(source-line);
    position: relative; left: -1em; text-align: right; vertical-align: baseline;
    border: none; display: inline-block;
    -webkit-touch-callout: none; -webkit-user-select: none;
    -khtml-user-select: none; -moz-user-select: none;
    -ms-user-select: none; user-select: none;
    padding: 0 4px; width: 4em;
    color: #aaaaaa;
  }
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa;  padding-left: 4px; }
div.sourceCode
  {   }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { color: #008000; } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { color: #008000; font-weight: bold; } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>


<script src="site_libs/quarto-nav/quarto-nav.js"></script>
<script src="site_libs/quarto-nav/headroom.min.js"></script>
<script src="site_libs/clipboard/clipboard.min.js"></script>
<script src="site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="site_libs/quarto-search/fuse.min.js"></script>
<script src="site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="./">
<link href="./tips.html" rel="next">
<link href="./04-data IO.html" rel="prev">
<script src="site_libs/quarto-html/quarto.js"></script>
<script src="site_libs/quarto-html/popper.min.js"></script>
<script src="site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="site_libs/quarto-html/anchor.min.js"></script>
<link href="site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="site_libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="site_libs/bootstrap/bootstrap.min.js"></script>
<link href="site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="site_libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
  "location": "sidebar",
  "copy-button": false,
  "collapse-after": 3,
  "panel-placement": "start",
  "type": "textbox",
  "limit": 20,
  "language": {
    "search-no-results-text": "No results",
    "search-matching-documents-text": "matching documents",
    "search-copy-link-title": "Copy link to search",
    "search-hide-matches-text": "Hide additional matches",
    "search-more-match-text": "more match in this document",
    "search-more-matches-text": "more matches in this document",
    "search-clear-button-title": "Clear",
    "search-detached-cancel-button-title": "Cancel",
    "search-submit-button-title": "Submit"
  }
}</script>

<link href="site_libs/pagedtable-1.1/css/pagedtable.css" rel="stylesheet">
<script src="site_libs/pagedtable-1.1/js/pagedtable.js"></script>


</head>

<body class="nav-sidebar floating">

<div id="quarto-search-results"></div>
  <header id="quarto-header" class="headroom fixed-top">
  <nav class="quarto-secondary-nav" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
    <div class="container-fluid d-flex justify-content-between">
      <h1 class="quarto-secondary-nav-title"><span class="chapter-number">5</span>&nbsp; <span class="chapter-title">数据清洗</span></h1>
      <button type="button" class="quarto-btn-toggle btn" aria-label="Show secondary navigation">
        <i class="bi bi-chevron-right"></i>
      </button>
    </div>
  </nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
  <nav id="quarto-sidebar" class="sidebar collapse sidebar-navigation floating overflow-auto">
    <div class="pt-lg-2 mt-2 text-left sidebar-header">
    <div class="sidebar-title mb-0 py-0">
      <a href="./">R语言医学数据科学入门</a> 
        <div class="sidebar-tools-main">
    <a href="" title="Share" id="sidebar-tool-dropdown-0" class="sidebar-tool dropdown-toggle px-1" data-bs-toggle="dropdown" aria-expanded="false"><i class="bi bi-share"></i></a>
    <ul class="dropdown-menu" aria-labelledby="sidebar-tool-dropdown-0">
        <li>
          <a class="dropdown-item sidebar-tools-main-item" href="https://twitter.com/intent/tweet?url=|url|">
            <i class="bi bi-bi-twitter pe-1"></i>
          Twitter
          </a>
        </li>
        <li>
          <a class="dropdown-item sidebar-tools-main-item" href="https://www.facebook.com/sharer/sharer.php?u=|url|">
            <i class="bi bi-bi-facebook pe-1"></i>
          Facebook
          </a>
        </li>
    </ul>
</div>
    </div>
      </div>
      <div class="mt-2 flex-shrink-0 align-items-center">
        <div class="sidebar-search">
        <div id="quarto-search" class="" title="Search"></div>
        </div>
      </div>
    <div class="sidebar-menu-container"> 
    <ul class="list-unstyled mt-1">
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./index.html" class="sidebar-item-text sidebar-link">Preface</a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./intro.html" class="sidebar-item-text sidebar-link">Introduction</a>
  </div>
</li>
        <li class="sidebar-item sidebar-item-section">
      <div class="sidebar-item-container"> 
            <a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" aria-expanded="true">Data things</a>
          <a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" aria-expanded="true">
            <i class="bi bi-chevron-right ms-2"></i>
          </a> 
      </div>
      <ul id="quarto-sidebar-section-1" class="collapse list-unstyled sidebar-section depth1 show">  
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./01-hello_data.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Hello data</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./02-Data types.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">数据结构和类型</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./03-tidy_data.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Tidy data</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./04-data IO.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">4</span>&nbsp; <span class="chapter-title">Data I/O</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./05-tidy_task.html" class="sidebar-item-text sidebar-link active"><span class="chapter-number">5</span>&nbsp; <span class="chapter-title">数据清洗</span></a>
  </div>
</li>
      </ul>
  </li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./tips.html" class="sidebar-item-text sidebar-link">Tips</a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./references.html" class="sidebar-item-text sidebar-link">References</a>
  </div>
</li>
    </ul>
    </div>
</nav>
<!-- margin-sidebar -->
    <div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
        <nav id="TOC" role="doc-toc" class="toc-active">
    <h2 id="toc-title">Table of contents</h2>
   
  <ul>
  <li><a href="#清洗步骤" id="toc-清洗步骤" class="nav-link active" data-scroll-target="#清洗步骤"><span class="toc-section-number">5.1</span>  清洗步骤</a></li>
  <li><a href="#列-行操作" id="toc-列-行操作" class="nav-link" data-scroll-target="#列-行操作"><span class="toc-section-number">5.2</span>  列-行操作</a>
  <ul class="collapse">
  <li><a href="#列选择-重命名-新列" id="toc-列选择-重命名-新列" class="nav-link" data-scroll-target="#列选择-重命名-新列"><span class="toc-section-number">5.2.1</span>  列[选择-重命名-新列]</a></li>
  <li><a href="#行操作-filter" id="toc-行操作-filter" class="nav-link" data-scroll-target="#行操作-filter"><span class="toc-section-number">5.2.2</span>  行操作 filter()</a></li>
  <li><a href="#分组和运算" id="toc-分组和运算" class="nav-link" data-scroll-target="#分组和运算"><span class="toc-section-number">5.2.3</span>  分组和运算</a></li>
  </ul></li>
  </ul>
</nav>
    </div>
<!-- main -->
<main class="content" id="quarto-document-content">

<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title d-none d-lg-block"><span class="chapter-number">5</span>&nbsp; <span class="chapter-title">数据清洗</span></h1>
</div>



<div class="quarto-title-meta">

    
  
    
  </div>
  

</header>

<p>前面，我们花了不少篇幅，做了一些基础性的操作。在正式进入数据可视化和分析以前，我们还要学会如何将导入的原始数据，通过某些操作 把数据转化成可以直接分析的整洁数据，这个过程就是数据清洗。英文名有很多，data cleaning，data wrangling，data manipulation，data munging, data transformation, data processing等</p>
<section id="清洗步骤" class="level2" data-number="5.1">
<h2 data-number="5.1" class="anchored" data-anchor-id="清洗步骤"><span class="header-section-number">5.1</span> 清洗步骤</h2>
<p>这些步骤，前三步，顺序在某些情况下可以变化，比如可以先数据变形</p>
<ol type="1">
<li>列操作</li>
<li>行操作</li>
<li>数据变形</li>
<li>数据归一</li>
<li>清除重复和空值</li>
<li>数据合并</li>
</ol>
</section>
<section id="列-行操作" class="level2" data-number="5.2">
<h2 data-number="5.2" class="anchored" data-anchor-id="列-行操作"><span class="header-section-number">5.2</span> 列-行操作</h2>
<p>想一想，拿到表格数据后，我们应该做些什么。首先就是先留下自己想要的，不需要的内容我们可以剔除，比如，病人的姓名是隐私，一般不需要(剔除列)；一些记录不符合纳入标准，需要剔除掉，比如患者年龄太小或太大(剔除行)。这就需要列-行的操作。先进行列操作，是我的习惯，你当然也可以先操作行。</p>
<p>需要加载的包，需要读取的数据如下</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>pacman<span class="sc">::</span><span class="fu">p_load</span>(tidyverse,rio)</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>stroke <span class="ot">&lt;-</span> <span class="fu">import</span>(<span class="st">"dataset/stroke.csv"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>在进行各种操作以前，我们一般先整体上看一下这个数据的状况，我们可以用一个函数<code>glimpse()</code></p>
<div class="cell">
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="fu">glimpse</span>(stroke)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 12
$ doa           &lt;chr&gt; "17/2/2011", "20/3/2011", "9/4/2011", "12/4/2011", "12/4…
$ dod           &lt;chr&gt; "18/2/2011", "21/3/2011", "10/4/2011", "13/4/2011", "13/…
$ status        &lt;chr&gt; "alive", "alive", "dead", "dead", "alive", "dead", "aliv…
$ sex           &lt;chr&gt; "male", "male", "female", "male", "female", "female", "m…
$ dm            &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes",…
$ gcs           &lt;int&gt; 15, 15, 11, 3, 15, 3, 11, 15, 6, 15, 15, 4, 4, 10, 12, 1…
$ sbp           &lt;int&gt; 151, 196, 126, 170, 103, 91, 171, 106, 170, 123, 144, 23…
$ dbp           &lt;int&gt; 73, 123, 78, 103, 62, 55, 80, 67, 90, 83, 89, 120, 120, …
$ wbc           &lt;dbl&gt; 12.5, 8.1, 15.3, 13.9, 14.7, 14.2, 8.7, 5.5, 10.5, 7.2, …
$ time2         &lt;int&gt; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
$ stroke_type   &lt;chr&gt; "IS", "IS", "HS", "IS", "IS", "HS", "IS", "IS", "HS", "I…
$ referral_from &lt;chr&gt; "non-hospital", "non-hospital", "hospital", "hospital", …</code></pre>
</div>
</div>
<div class="callout-note callout callout-style-default callout-captioned">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-caption-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>该数据集的变量名解释 - doa : date of admission<br>
- dod : date of discharge - status : event at discharge (alive or dead)<br>
- sex : male or female<br>
- dm : diabetes (yes or no)<br>
- gcs : Glasgow Coma Scale (value from 3 to 15)<br>
- sbp : Systolic blood pressure (mmHg)<br>
- dbp : Diastolic blood pressure (mmHg)<br>
- wbc : Total white cell count<br>
- time2 : days in ward<br>
- stroke_type : stroke type (Ischaemic stroke or Haemorrhagic stroke)<br>
- referral_from : patient was referred from a hospital or not from a hospital</p>
</div>
</div>
<section id="列选择-重命名-新列" class="level3" data-number="5.2.1">
<h3 data-number="5.2.1" class="anchored" data-anchor-id="列选择-重命名-新列"><span class="header-section-number">5.2.1</span> 列[选择-重命名-新列]</h3>
<p>列-行操作，用到的包主要是<code>dplyr</code>，隶属于tidyverse系列，按照习惯，我们直接加载tidyverse即可(前面已经加载过)。</p>
<section id="选择列select" class="level4" data-number="5.2.1.1">
<h4 data-number="5.2.1.1" class="anchored" data-anchor-id="选择列select"><span class="header-section-number">5.2.1.1</span> 选择列select()</h4>
<p>通过列号或者列名选择</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb4"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>stroke2 <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">select</span>(<span class="dv">1</span>,<span class="dv">3</span>,sex,dm,stroke_type) <span class="sc">%&gt;%</span> </span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 5
$ doa         &lt;chr&gt; "17/2/2011", "20/3/2011", "9/4/2011", "12/4/2011", "12/4/2…
$ status      &lt;chr&gt; "alive", "alive", "dead", "dead", "alive", "dead", "alive"…
$ sex         &lt;chr&gt; "male", "male", "female", "male", "female", "female", "mal…
$ dm          &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes", "…
$ stroke_type &lt;chr&gt; "IS", "IS", "HS", "IS", "IS", "HS", "IS", "IS", "HS", "IS"…</code></pre>
</div>
</div>
<p>有时候,我们希望大部分列都保留,只剔除不想要的列,只需在列号或列名前加<code>-</code></p>
<div class="cell">
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>stroke3 <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">select</span>(<span class="sc">-</span><span class="dv">1</span>,<span class="sc">-</span>sex) <span class="sc">%&gt;%</span> </span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 10
$ dod           &lt;chr&gt; "18/2/2011", "21/3/2011", "10/4/2011", "13/4/2011", "13/…
$ status        &lt;chr&gt; "alive", "alive", "dead", "dead", "alive", "dead", "aliv…
$ dm            &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes",…
$ gcs           &lt;int&gt; 15, 15, 11, 3, 15, 3, 11, 15, 6, 15, 15, 4, 4, 10, 12, 1…
$ sbp           &lt;int&gt; 151, 196, 126, 170, 103, 91, 171, 106, 170, 123, 144, 23…
$ dbp           &lt;int&gt; 73, 123, 78, 103, 62, 55, 80, 67, 90, 83, 89, 120, 120, …
$ wbc           &lt;dbl&gt; 12.5, 8.1, 15.3, 13.9, 14.7, 14.2, 8.7, 5.5, 10.5, 7.2, …
$ time2         &lt;int&gt; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
$ stroke_type   &lt;chr&gt; "IS", "IS", "HS", "IS", "IS", "HS", "IS", "IS", "HS", "I…
$ referral_from &lt;chr&gt; "non-hospital", "non-hospital", "hospital", "hospital", …</code></pre>
</div>
</div>
</section>
<section id="重命名列rename" class="level4" data-number="5.2.1.2">
<h4 data-number="5.2.1.2" class="anchored" data-anchor-id="重命名列rename"><span class="header-section-number">5.2.1.2</span> 重命名列rename()</h4>
<p>对列名字不太满意?</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb8"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>stroke3 <span class="sc">%&gt;%</span> </span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">rename</span>(<span class="at">type =</span> stroke_type, <span class="at">DM=</span>dm) <span class="sc">%&gt;%</span> </span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 10
$ dod           &lt;chr&gt; "18/2/2011", "21/3/2011", "10/4/2011", "13/4/2011", "13/…
$ status        &lt;chr&gt; "alive", "alive", "dead", "dead", "alive", "dead", "aliv…
$ DM            &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes",…
$ gcs           &lt;int&gt; 15, 15, 11, 3, 15, 3, 11, 15, 6, 15, 15, 4, 4, 10, 12, 1…
$ sbp           &lt;int&gt; 151, 196, 126, 170, 103, 91, 171, 106, 170, 123, 144, 23…
$ dbp           &lt;int&gt; 73, 123, 78, 103, 62, 55, 80, 67, 90, 83, 89, 120, 120, …
$ wbc           &lt;dbl&gt; 12.5, 8.1, 15.3, 13.9, 14.7, 14.2, 8.7, 5.5, 10.5, 7.2, …
$ time2         &lt;int&gt; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
$ type          &lt;chr&gt; "IS", "IS", "HS", "IS", "IS", "HS", "IS", "IS", "HS", "I…
$ referral_from &lt;chr&gt; "non-hospital", "non-hospital", "hospital", "hospital", …</code></pre>
</div>
</div>
<p>其实,如果我们用<code>select()</code>命令,在选择行的同时,可以将重命名同时进行。</p>
<div class="callout-tip callout callout-style-default callout-captioned">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-caption-container flex-fill">
Tip
</div>
</div>
<div class="callout-body-container callout-body">
<p>想想，这样做和<code>rename()</code>有什么区别。</p>
</div>
</div>
<div class="cell">
<div class="sourceCode cell-code" id="cb10"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>stroke4 <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">select</span>( <span class="at">gender =</span> sex, <span class="at">DM =</span> dm) <span class="sc">%&gt;%</span> </span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 2
$ gender &lt;chr&gt; "male", "male", "female", "male", "female", "female", "male", "…
$ DM     &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes", "no", …</code></pre>
</div>
</div>
</section>
<section id="创建新列-mutate" class="level4" data-number="5.2.1.3">
<h4 data-number="5.2.1.3" class="anchored" data-anchor-id="创建新列-mutate"><span class="header-section-number">5.2.1.3</span> 创建新列 mutate()</h4>
<p>我们想创建一个新列，是脉压值，pulse_p = 收缩压-舒张压。可以用mutate()</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a>stroke5 <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">select</span>(<span class="sc">-</span><span class="dv">1</span>,<span class="sc">-</span>sex) <span class="sc">%&gt;%</span> </span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">mutate</span>(<span class="at">pulse_p =</span> sbp <span class="sc">-</span> dbp) <span class="sc">%&gt;%</span> </span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 11
$ dod           &lt;chr&gt; "18/2/2011", "21/3/2011", "10/4/2011", "13/4/2011", "13/…
$ status        &lt;chr&gt; "alive", "alive", "dead", "dead", "alive", "dead", "aliv…
$ dm            &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes",…
$ gcs           &lt;int&gt; 15, 15, 11, 3, 15, 3, 11, 15, 6, 15, 15, 4, 4, 10, 12, 1…
$ sbp           &lt;int&gt; 151, 196, 126, 170, 103, 91, 171, 106, 170, 123, 144, 23…
$ dbp           &lt;int&gt; 73, 123, 78, 103, 62, 55, 80, 67, 90, 83, 89, 120, 120, …
$ wbc           &lt;dbl&gt; 12.5, 8.1, 15.3, 13.9, 14.7, 14.2, 8.7, 5.5, 10.5, 7.2, …
$ time2         &lt;int&gt; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
$ stroke_type   &lt;chr&gt; "IS", "IS", "HS", "IS", "IS", "HS", "IS", "IS", "HS", "I…
$ referral_from &lt;chr&gt; "non-hospital", "non-hospital", "hospital", "hospital", …
$ pulse_p       &lt;int&gt; 78, 73, 48, 67, 41, 36, 91, 39, 80, 40, 55, 110, 87, 79,…</code></pre>
</div>
</div>
<div class="callout-note callout callout-style-default callout-captioned">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-caption-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>留个作业，如果你想创建一个新列，收缩压&gt;140或舒张压&gt;90为高血压，并赋值为HBP，其余赋值为norm。如何做？</p>
<p>提示：我们可以用<code>ifelse</code>这个语句，ifelse(sbp&gt;140|dbp&gt;90, ‘HBP’, ‘norm’)</p>
</div>
</div>
</section>
<section id="列的数据类型转换-mutate" class="level4" data-number="5.2.1.4">
<h4 data-number="5.2.1.4" class="anchored" data-anchor-id="列的数据类型转换-mutate"><span class="header-section-number">5.2.1.4</span> 列的数据类型转换 mutate()</h4>
<div class="cell">
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a>stroke5 <span class="sc">%&gt;%</span> </span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">mutate</span>(<span class="at">status =</span> <span class="fu">as.factor</span>(status)) <span class="sc">%&gt;%</span> </span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 213
Columns: 11
$ dod           &lt;chr&gt; "18/2/2011", "21/3/2011", "10/4/2011", "13/4/2011", "13/…
$ status        &lt;fct&gt; alive, alive, dead, dead, alive, dead, alive, alive, dea…
$ dm            &lt;chr&gt; "no", "no", "no", "no", "yes", "no", "no", "yes", "yes",…
$ gcs           &lt;int&gt; 15, 15, 11, 3, 15, 3, 11, 15, 6, 15, 15, 4, 4, 10, 12, 1…
$ sbp           &lt;int&gt; 151, 196, 126, 170, 103, 91, 171, 106, 170, 123, 144, 23…
$ dbp           &lt;int&gt; 73, 123, 78, 103, 62, 55, 80, 67, 90, 83, 89, 120, 120, …
$ wbc           &lt;dbl&gt; 12.5, 8.1, 15.3, 13.9, 14.7, 14.2, 8.7, 5.5, 10.5, 7.2, …
$ time2         &lt;int&gt; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
$ stroke_type   &lt;chr&gt; "IS", "IS", "HS", "IS", "IS", "HS", "IS", "IS", "HS", "I…
$ referral_from &lt;chr&gt; "non-hospital", "non-hospital", "hospital", "hospital", …
$ pulse_p       &lt;int&gt; 78, 73, 48, 67, 41, 36, 91, 39, 80, 40, 55, 110, 87, 79,…</code></pre>
</div>
</div>
</section>
</section>
<section id="行操作-filter" class="level3" data-number="5.2.2">
<h3 data-number="5.2.2" class="anchored" data-anchor-id="行操作-filter"><span class="header-section-number">5.2.2</span> 行操作 filter()</h3>
<p>行操作的需求一般就只有一个，把我要的记录筛选出来。</p>
<p>比如我们创建一个名为stroke_m_9的数据集，筛选出Glasgow Coma Scale (gcs)&gt;9分以上的男性。</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>stroke_m_9 <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">filter</span>(sex <span class="sc">==</span> <span class="st">"male"</span>, gcs<span class="sc">&gt;</span><span class="dv">9</span>) <span class="sc">%&gt;%</span> </span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">glimpse</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Rows: 82
Columns: 12
$ doa           &lt;chr&gt; "17/2/2011", "20/3/2011", "22/5/2011", "28/11/2011", "25…
$ dod           &lt;chr&gt; "18/2/2011", "21/3/2011", "23/5/2011", "29/11/2011", "26…
$ status        &lt;chr&gt; "alive", "alive", "alive", "dead", "alive", "alive", "al…
$ sex           &lt;chr&gt; "male", "male", "male", "male", "male", "male", "male", …
$ dm            &lt;chr&gt; "no", "no", "no", "no", "no", "no", "no", "no", "no", "y…
$ gcs           &lt;int&gt; 15, 15, 11, 10, 14, 15, 15, 15, 15, 15, 15, 15, 15, 14, …
$ sbp           &lt;int&gt; 151, 196, 171, 207, 128, 143, 161, 153, 143, 116, 132, 1…
$ dbp           &lt;int&gt; 73, 123, 80, 128, 79, 59, 107, 61, 93, 81, 81, 72, 146, …
$ wbc           &lt;dbl&gt; 12.5, 8.1, 8.7, 10.8, 10.3, 7.1, 9.5, 11.2, 15.6, 11.0, …
$ time2         &lt;int&gt; 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,…
$ stroke_type   &lt;chr&gt; "IS", "IS", "IS", "HS", "IS", "IS", "IS", "IS", "IS", "I…
$ referral_from &lt;chr&gt; "non-hospital", "non-hospital", "hospital", "non-hospita…</code></pre>
</div>
</div>
</section>
<section id="分组和运算" class="level3" data-number="5.2.3">
<h3 data-number="5.2.3" class="anchored" data-anchor-id="分组和运算"><span class="header-section-number">5.2.3</span> 分组和运算</h3>
<p>有时候我们很想对数据进行分组，并分开计算。如我们想计算男女之间的血压均值分别是多少。可以分别用到<code>group_by()</code>和<code>summarize()</code>。</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>stroke_sex <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">group_by</span>(sex) <span class="sc">%&gt;%</span> </span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">summarise</span>(<span class="at">meansbp =</span> <span class="fu">mean</span>(sbp, <span class="at">na.rm =</span> <span class="cn">TRUE</span>), <span class="co"># na.rm参数是剔除空值</span></span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>            <span class="at">meandbp  =</span> <span class="fu">mean</span>(dbp, <span class="at">na.rm =</span> <span class="cn">TRUE</span>),</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>            <span class="at">meangcs =</span> <span class="fu">mean</span>(gcs, <span class="at">na.rm =</span> <span class="cn">TRUE</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>还可试试计算统计频数，如status这个代表是生存还是死亡。</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb19"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a>stroke_status <span class="ot">&lt;-</span> stroke <span class="sc">%&gt;%</span> </span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">group_by</span>(sex) <span class="sc">%&gt;%</span> </span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>  <span class="fu">count</span>(status, <span class="at">sort =</span> <span class="cn">TRUE</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>关于列-行操作，我们来总结一下<code>dplyr</code>的主要操作。</p>
<p>大家要学会找速查表（cheatsheet），直接在搜索引擎搜索，某包的名字+cheatsheet即可，如dplyr cheatsheet。</p>
<p>https://github.com/rstudio/cheatsheets/blob/main/data-transformation.pdf</p>
<ul>
<li><code>mutate()</code> adds new variables that are functions of existing variables</li>
<li><code>select()</code> picks variables based on their names.</li>
<li><code>filter()</code> picks cases based on their values.</li>
<li><code>summarise()</code> reduces multiple values down to a single summary.</li>
<li><code>arrange()</code> changes the ordering of the rows.</li>
</ul>


</section>
</section>

</main> <!-- /main -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
  const toggleBodyColorMode = (bsSheetEl) => {
    const mode = bsSheetEl.getAttribute("data-mode");
    const bodyEl = window.document.querySelector("body");
    if (mode === "dark") {
      bodyEl.classList.add("quarto-dark");
      bodyEl.classList.remove("quarto-light");
    } else {
      bodyEl.classList.add("quarto-light");
      bodyEl.classList.remove("quarto-dark");
    }
  }
  const toggleBodyColorPrimary = () => {
    const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
    if (bsSheetEl) {
      toggleBodyColorMode(bsSheetEl);
    }
  }
  toggleBodyColorPrimary();  
  const icon = "";
  const anchorJS = new window.AnchorJS();
  anchorJS.options = {
    placement: 'right',
    icon: icon
  };
  anchorJS.add('.anchored');
  const clipboard = new window.ClipboardJS('.code-copy-button', {
    target: function(trigger) {
      return trigger.previousElementSibling;
    }
  });
  clipboard.on('success', function(e) {
    // button target
    const button = e.trigger;
    // don't keep focus
    button.blur();
    // flash "checked"
    button.classList.add('code-copy-button-checked');
    var currentTitle = button.getAttribute("title");
    button.setAttribute("title", "Copied!");
    let tooltip;
    if (window.bootstrap) {
      button.setAttribute("data-bs-toggle", "tooltip");
      button.setAttribute("data-bs-placement", "left");
      button.setAttribute("data-bs-title", "Copied!");
      tooltip = new bootstrap.Tooltip(button, 
        { trigger: "manual", 
          customClass: "code-copy-button-tooltip",
          offset: [0, -8]});
      tooltip.show();    
    }
    setTimeout(function() {
      if (tooltip) {
        tooltip.hide();
        button.removeAttribute("data-bs-title");
        button.removeAttribute("data-bs-toggle");
        button.removeAttribute("data-bs-placement");
      }
      button.setAttribute("title", currentTitle);
      button.classList.remove('code-copy-button-checked');
    }, 1000);
    // clear code selection
    e.clearSelection();
  });
  function tippyHover(el, contentFn) {
    const config = {
      allowHTML: true,
      content: contentFn,
      maxWidth: 500,
      delay: 100,
      arrow: false,
      appendTo: function(el) {
          return el.parentElement;
      },
      interactive: true,
      interactiveBorder: 10,
      theme: 'quarto',
      placement: 'bottom-start'
    };
    window.tippy(el, config); 
  }
  const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
  for (var i=0; i<noterefs.length; i++) {
    const ref = noterefs[i];
    tippyHover(ref, function() {
      // use id or data attribute instead here
      let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
      try { href = new URL(href).hash; } catch {}
      const id = href.replace(/^#\/?/, "");
      const note = window.document.getElementById(id);
      return note.innerHTML;
    });
  }
  const findCites = (el) => {
    const parentEl = el.parentElement;
    if (parentEl) {
      const cites = parentEl.dataset.cites;
      if (cites) {
        return {
          el,
          cites: cites.split(' ')
        };
      } else {
        return findCites(el.parentElement)
      }
    } else {
      return undefined;
    }
  };
  var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
  for (var i=0; i<bibliorefs.length; i++) {
    const ref = bibliorefs[i];
    const citeInfo = findCites(ref);
    if (citeInfo) {
      tippyHover(citeInfo.el, function() {
        var popup = window.document.createElement('div');
        citeInfo.cites.forEach(function(cite) {
          var citeDiv = window.document.createElement('div');
          citeDiv.classList.add('hanging-indent');
          citeDiv.classList.add('csl-entry');
          var biblioDiv = window.document.getElementById('ref-' + cite);
          if (biblioDiv) {
            citeDiv.innerHTML = biblioDiv.innerHTML;
          }
          popup.appendChild(citeDiv);
        });
        return popup.innerHTML;
      });
    }
  }
});
</script>
<nav class="page-navigation">
  <div class="nav-page nav-page-previous">
      <a href="./04-data IO.html" class="pagination-link">
        <i class="bi bi-arrow-left-short"></i> <span class="nav-page-text"><span class="chapter-number">4</span>&nbsp; <span class="chapter-title">Data I/O</span></span>
      </a>          
  </div>
  <div class="nav-page nav-page-next">
      <a href="./tips.html" class="pagination-link">
        <span class="nav-page-text">Tips</span> <i class="bi bi-arrow-right-short"></i>
      </a>
  </div>
</nav>
</div> <!-- /content -->



</body></html>